import { useOrganizationalStore } from '';
import { Button, Input, Tree } from 'antd';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import styles from './index.less'
import { useModel } from '@umijs/max';
const { Search } = Input;

const getParentKey: any = (key: string, tree: any[]) => {
  let parentKey;

  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];

    if (node.children) {
      // console.log({ node })
      if (node.children.some((item: { id: string; }) => item.id == key)) {
        parentKey = node.id;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }

  return parentKey;
};


interface Iprops {
  hide: () => void
}

const DepTree: React.FC<Iprops> = (props) => {
  const { hide } = props
  const flatList = useRef<any[]>([])
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const { data, setCurrentPosi } = useModel('organizational')

  const [posi, setPosi] = useState<any[]>([])

  const generateList = (data: any[]) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const { id } = node;
      flatList.current.push({
        key: id,
        title: node.short_name || node.title,
      });

      if (node.children) {
        generateList(node.children);
      }
    }
  };

  useEffect(() => {
    generateList(data)
  }, [data])

  const onExpand = (newExpandedKeys: any[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const onChange = useCallback((e: any) => {
    const { value } = e.target;
    const newExpandedKeys = flatList.current.map((item) => {
      if (item.title.indexOf(value) > -1) {
        return getParentKey(item.key, data);
      }
      return null;
    }).filter((item, i, self) => item && self.indexOf(item) === i);
    setExpandedKeys(newExpandedKeys);
    setSearchValue(value);
    setAutoExpandParent(true);
  }, [data]);

  const treeData = useMemo(() => {
    const loop: any = (data: any[]) => {
      return data.map((item) => {
        const strTitle = item.short_name || item.title;
        const index = strTitle.indexOf(searchValue);
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + searchValue.length);
        const title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span className={styles.red}>{searchValue}</span>
              {afterStr}
            </span>
          ) : (
            <span>{strTitle}</span>
          );

        if (item.children) {
          return {
            title,
            key: item.id,
            children: loop(item.children),
          };
        }
        return {
          title,
          key: item.id,
        };
      });
    }
    console.log(loop(data))
    return loop(data);
  }, [searchValue, data]);

  const select = (_selectedKeys: any[], info: any) => {
    const arr = info.node.pos.split('-')
    let list = data
    let pos: any[] = []
    for (let i = 1; i < arr.length; i++) {
      const item = arr[i]
      const current = list[item]
      list = current.children
      pos.push(current)
    }
    setPosi(pos)
  }

  const onConfrim = () => {
    console.log(posi)
    setCurrentPosi(posi)
    hide()
  }

  return (
    <div className={styles.dep}>
      <div className={styles.header}>
        <Search
          placeholder="输入关键字搜索"
          onChange={onChange}
        />
      </div>
      <Tree
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={true}
        treeData={treeData}
        className={styles.tree}
        onSelect={select}
      />
      <div className={styles.footer}>
        <div className={styles.left}>当前选择：{posi.map(item => item.short_name).join(' /')}</div>
        <div className={styles.right}>
          <Button type='primary' className={styles.confirm} onClick={onConfrim}>确认</Button>
          <Button onClick={hide}>取消</Button>
        </div>
      </div>
    </div>
  );
};

export default DepTree;